import { defineStore } from 'pinia'
import type { UserState } from './types/type'
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user'
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
import {
  LoginFormReq,
  LoginResponseData,
  UserInfoResponseData,
} from '@/api/user/type'
import { routes, asyncRoute, anyRoute } from '@/router/routes'
import router from '@/router'
import cloneDeep from 'lodash/cloneDeep'
const filterRoutes = (asyncRoute: any, routes: any) => {
  let newRoutes: any = []
  asyncRoute.forEach((r: any) => {
    if (routes.includes(r.name)) {
      newRoutes.push(r)
      if(r.children && r.children.length>0){
        r.children = filterRoutes(r.children,routes)
      }
    }
  })
  return newRoutes
}
const useUserStore = defineStore('User', {
  state: (): UserState => {
    return {
      token: GET_TOKEN(),
      constRoutes: routes,
      buttons: [],
      username: '',
      avatar: '',
    }
  },
  actions: {
    userLogin(data: LoginFormReq) {
      return new Promise((resolve, reject) => {
        reqLogin(data).then((res: LoginResponseData) => {
          if (res.code == 200) {
            this.token = res.data as string
            SET_TOKEN(res.data as string)
            resolve('ok')
          } else {
            reject(res.data)
          }
        })
      })
    },
    userInfo() {
      return new Promise((resolve, reject) => {
        reqUserInfo().then((res: UserInfoResponseData) => {
          if (res.code == 200) {
            this.username = res.data.name
            this.avatar = res.data.avatar
            this.buttons = res.data.buttons
            let useAsyncRoute = filterRoutes(cloneDeep(asyncRoute),res.data.routes)
            this.constRoutes = [...routes,...useAsyncRoute,anyRoute]
            this.constRoutes.forEach((item) => {
              router.addRoute(item)
            })
            resolve('ok')
          } else {
            reject(res.data)
          }
        })
      })
    },
    userLogout() {
      return new Promise((resolve, reject) => {
        reqLogout().then((res: any) => {
          if (res.code == '200') {
            this.token = ''
            this.username = ''
            this.avatar = ''
            REMOVE_TOKEN()
            resolve('ok')
          } else {
            reject(res.data)
          }
        })
      })
    },
  },
  getters: {},
})
export default useUserStore
